package com.zhao.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhao.eduservice.entity.EduChapter;
import com.zhao.eduservice.entity.EduVideo;
import com.zhao.eduservice.entity.chapter.ChapterVo;
import com.zhao.eduservice.entity.chapter.VideoVo;
import com.zhao.eduservice.mapper.EduChapterMapper;
import com.zhao.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.eduservice.service.EduVideoService;
import com.zhao.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author test_java
 * @since 2022-10-18
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService videoService;

    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        // 1.根据课程ID 查询出对应的章节
        QueryWrapper<EduChapter> wrapperChapter = new QueryWrapper<>();
        wrapperChapter.eq("course_id",courseId);
        List<EduChapter> eduChapters = baseMapper.selectList(wrapperChapter);
        // 2.根据课程ID查询小节
        QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
        wrapperChapter.eq("course_id",courseId);
        List<EduVideo> eduVideos = videoService.list(wrapperVideo);

        List<ChapterVo> finalList = new ArrayList<>();

        // 3.遍历查询出来的章节
        for (int i = 0; i < eduChapters.size() ; i++) {
            EduChapter eduChapter = eduChapters.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            finalList.add(chapterVo);

            List<VideoVo> finalVideoVo = new ArrayList<>();
            // 4.遍历查询出来的小节
            for (int j = 0; j < eduVideos.size(); j++) {
                EduVideo eduVideo = eduVideos.get(i);
                if (eduVideo.getChapterId().equals(eduChapter.getId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(eduVideo,videoVo);
                    finalVideoVo.add(videoVo);
                }
            }
            chapterVo.setChildren(finalVideoVo);
        }
        return finalList;
    }

    @Override // 查看章节下是否有小节，如果有，不能删除
    public boolean deleteChapter(String chapterId) {
        // 根据章节id查询小节
        QueryWrapper<EduVideo> wrapper =new QueryWrapper();
        wrapper.eq("chapter_id",chapterId);
        int count = videoService.count(wrapper);
        if (count > 0){
            // 不删除
            throw new GuliException(20001,"不能删除");
        }else {
            // 删除章节
            int res = baseMapper.deleteById(chapterId);
            return res > 0;
        }
    }
}
